#!/usr/bin/env python3.11
# -*- encoding: utf-8 -*-
"""
@File    :   controllers.py
@Time    :   2024/06/17 10:42:45
@Author  :   windstarry 
@Version :   1.0
"""
# here put the import lib
from django.forms.models import model_to_dict
from ninja_extra import api_controller, route
from ninja_extra.permissions import IsAuthenticated
from ninja_jwt.authentication import JWTAuth

from core.schemas import MsgSchema,DataSchema
from core.utils import list_to_tree
from .schemas import MenuInfoSchema, MenuInSchema
from .mixins import MenuMixin


@api_controller("/menus", tags=["菜单管理"], auth=JWTAuth())
class MenuController(MenuMixin):
    @route.get(
        "",
        summary="菜单信息",
        url_name="menu_list",
        response=[(200, DataSchema), (400, MsgSchema)],
        permissions=[IsAuthenticated],
    )
    def get_menus_info(
        self,
    ):
        menus = [
            model_to_dict(
                menu,
                fields=[
                    "id",
                    "name",
                    "icon",
                    "path",
                    "pid",
                    "sort",
                    "type",
                    "component",
                    "identifier",
                    "api",
                    "method",
                ],
            )
            for menu in self.get_queryset()
        ]
        try:
            return dict(data=list_to_tree(menus))
        except KeyError:
            return dict(detail="菜单根节点丢失")

    @route.post(
        "",
        summary="创建菜单",
        url_name="create_menu",
        response=[(201, MenuInfoSchema), (400, MsgSchema)],
        permissions=[IsAuthenticated],
    )
    def create_menu(self, data: MenuInSchema):
        obj = data.create()
        return 201, obj

    @route.delete(
        "/{mid}",
        response=[(200, MsgSchema), (400, MsgSchema)],
        summary="删除菜单",
        url_name="delete-menu",
        permissions=[IsAuthenticated],
    )
    def delete_menu(self, mid: int):
        if self.check_pid_status(mid):
            return 400, dict(detail="请先删除子节点")
        obj = self.get_object_or_exception(
            self.get_queryset(),
            id=mid,
            error_message="菜单不存在",
        )
        obj.delete()
        return 200, dict(detail="删除成功")

    @route.generic(
        "/{mid}",
        methods=["PUT"],
        response={200: MenuInfoSchema},
        summary="修改菜单",
        url_name="update-menu",
        permissions=[IsAuthenticated],
    )
    def update_menu(self, mid: int, data: MenuInSchema):
        obj = self.get_object_or_exception(
            self.get_queryset(), id__exact=mid, error_message="菜单不存在"
        )
        data.update(obj)
        return 200, obj
